--===========================================================================--
-- Naziv		: Data memory
-- Ime fajla	: DMem.vhdl  
-- Verzija		: 0.2
--===========================================================================-- 

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity DMem is 
	  port (
		   --reset : in  std_logic; --cemo ovo sluzi?	
			--IN
				clk2,D_RD,D_WR : in std_logic; --takt i kontrolne linije
				D_ABUS : in natural range 0 to 2**16 - 1; --Adresna magistrala za instrukcije 
			--INOUT
				--samo out jer se instrukcije samo citaju
				D_DBUS : inout std_logic_vector(15 downto 0) --Data magistrala za instrukcije    	   
	  );
end;

architecture DMem_AR of DMem is

	-- Build a 2-D array type for the RAM
	subtype word_t is std_logic_vector(15 downto 0);
	type memory_t is array(2**16-1 downto 0) of word_t;
	--type memory_t is array(word_t range <>) of word_t;

	function init_ram
		return memory_t is 
		variable tmp : memory_t := (others => (others => '0'));
	begin 
		for addr_pos in 0 to 2**16 - 1 loop 
			-- Initialize each address with the address itself
			tmp(addr_pos) := std_logic_vector(to_unsigned(addr_pos, 16));
		end loop;
		return tmp;
	end init_ram;

	-- Declare the RAM signal.	
	signal ram : memory_t := init_ram;

	-- Register to hold the address 
	signal addr_reg : natural range 0 to 2**16-1;

begin
	DMem_PR: process (clk2) is
	begin
	if (falling_edge(clk2)) then --memorija okida na opadajucu ivicu takta. svodi se na kasnjenje, ali sta sad...
		if(D_WR = '1') then
			ram(D_ABUS) <= D_DBUS;
		end if;
		
		--if(I_RD = '1') then
			--I_DBUS <= ram(I_ABUS);
		--end if;
		
		-- Register the address for reading
		addr_reg <= D_ABUS;
	end if;
	end process;
	
	D_DBUS <= ram(addr_reg);
end DMem_AR;